package me.chan.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.io.IOException;
import java.net.InetSocketAddress;

public class EventLoopClient {

    public static void main(String[] args) throws InterruptedException, IOException {

        ChannelFuture channelFuture = new Bootstrap()
                                .group(new NioEventLoopGroup())
                                .channel(NioSocketChannel.class)
                                .handler(new ChannelInitializer<NioSocketChannel>() {
                                    @Override
                                    protected void initChannel(NioSocketChannel socketChannel) throws Exception {
                                        socketChannel.pipeline().addLast(new StringEncoder());
                                    }
                                }).connect(new InetSocketAddress("127.0.0.1", 8080));

        // 1. sync
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        System.out.println(channel);
//        channel.writeAndFlush("hello world");

        // 2. channelListener
            channelFuture.addListener((ChannelFuture cf) -> {
                Channel channel = cf.channel();
                channel.writeAndFlush("hello world");
        });
    }
}
